<template>
  <div>
    <t-link  theme="primary" @click="handleOpenDialog">
      {{ name.toFixed(2) }}
    </t-link>
    <!-- 自定义对话框 -->
    <t-dialog v-model:visible="visible" attach="body" header="修改成本" width="50%">
      
         <!-- 自定义搜索 -->
        <!-- <custom-search ref="customSearchRef" v-slot="{ params }" @submit="handleInitTable" >
          <t-col :span="4">
            <t-form-item label="项目类型" name="projectName">
              <t-input v-model:value="params.projectName" clearable placeholder="" />
            </t-form-item>
          </t-col>
          <t-col :span="4">
            <t-form-item label="房屋户型" name="houseType">
              <t-select
                v-model:value="params.houseType"
                :options="dictionaryStore.get('decoration_order_house_type')"
                clearable
                filterable
                placeholder=""
              />
            </t-form-item>
          </t-col>
        </custom-search> -->
      <custom-table
        ref="customTableRef"
        row-key="id"
        :columns="columnsLaborTable"
        :api="programmeCostCRUD.page"
        column-controller-key="laborCostsList"
        v-if="materialDataType==='3'"
      >   
        <template #topContent>
          <div style="margin-bottom: var(--td-comp-margin-xxl);">
            <t-button
              @click="handleAdd"
            >
              新增成本
            </t-button>
          </div>
        </template>
        <template #houseType="{ row }">
          {{ dictionaryStore.analysis('decoration_order_house_type', row.houseType) }}
        </template>
        <template #fileUrl="{ row }">
          <image-viewer :images="[row.fileUrl]" width="80px" height="80px" v-if="row.fileUrl" />
        </template>
        <template #unit="{ row }">
          {{ dictionaryStore.analysis('unit', row.unit) }}
        </template>
        <template #num="{ row }">
          <t-input-number
          v-model:value="row.num"
          placeholder="请输入数量"
          clearable
          style="width: 100%"
          :min="1"
          :decimal-places="2"
    
        />
        </template>
        
        <template #operation="{ row, rowIndex }">
          <t-space>
            <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete(rowIndex)">
              <t-link theme="danger"> 删除 </t-link>
            </t-popconfirm>
          </t-space>
        </template>
      </custom-table>
      <custom-table
        ref="customTableRef"
        row-key="id"
        :columns="columnsTypeTable"
        :api="programmeCostCRUD.page"
        column-controller-key="laborCostsList"
        v-else
      >   
        <template #topContent>
          <div style="margin-bottom: var(--td-comp-margin-xxl);">
            <t-button
              @click="handleAdd"
            >
              新增成本
            </t-button>
          </div>
        </template>
        <template #houseType="{ row }">
          {{ dictionaryStore.analysis('decoration_order_house_type', row.houseType) }}
        </template>
        <template #fileUrl="{ row }">
          <image-viewer :images="[row.fileUrl]" width="80px" height="80px" v-if="row.fileUrl" />
        </template>
        <template #unit="{ row }">
          {{ dictionaryStore.analysis('unit', row.unit) }}
        </template>
        <template #num="{ row }">
          <t-input-number
          v-model:value="row.num"
          placeholder="请输入数量"
          clearable
          style="width: 100%"
          :min="1"
          :decimal-places="2"
    
        />
        </template>
        
        <template #operation="{ row,rowIndex }">
          <t-space>
            <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete(rowIndex)">
              <t-link theme="danger"> 删除 </t-link>
            </t-popconfirm>
          </t-space>
        </template>
      </custom-table>
       
      <template #footer>
        <t-button theme="default" @click="visible = false">取消</t-button>
        <t-button theme="warning" @click="handleReset">重置</t-button>
        <t-button :loading="loadingSubmit" @click="handleSave">保存</t-button>
      </template>
    </t-dialog>
    <cost-selection-dialog
      v-model:visible="visibleCost"
      :type="materialDataType"
      @save="handleCostSave"
    />
  </div>
</template>

<script setup lang="ts">
import { MessagePlugin, TableCol, TreeNodeModel } from 'tdesign-vue-next';
import { useTemplateRef,ref } from 'vue';

import { programmeCostCRUD, updateCost } from '@/api/budget/programme';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import ImageViewer from '@/components/image-viewer/index.vue';
import CostSelectionDialog from './CostSelectionDialog.vue';

import { useDictionaryStore } from '@/store';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// props
const props = defineProps({
  obj:{
    type:Object,
    default:{}
  },
  name:{
    type:Number,
    default:''
  },
  materialDataType:{
    type:String,
    require: true
  }
});
// emits
const emits = defineEmits(['requestSuccess']);
const visibleCost = ref(false)
// emits
// const emits = defineEmits(['requestSuccess']);
// // 自定义对话框ref
// // const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = () => {
  visible.value = true;
  handleInitTable();
};
// // 处理对话框请求成功
// const handleDialogRequestSuccess = (result: Record<string, any>) => {
//   emits('requestSuccess', result);
// };
const visible = ref(false)
// 自定义搜索ref
// const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columnsLaborTable: TableCol[] = [
  // { colKey: 'projectName', title: '项目类型' },
  { colKey: 'houseType', title: '房屋类型' },
  { colKey: 'unit', title: '单位' },
  { colKey: 'costPrice', title: '单价(元)' },
  { colKey: 'remark', title: '备注' },
  { colKey: 'num', title: '数量',width:160 },
  { colKey: 'operation', title: '操作',  fixed: 'right' },
];
// columns
const columnsTypeTable: TableCol[] = [
  { colKey: 'fileUrl', title: '封面图' },
  { colKey: 'name', title: '材料名称' },
  { colKey: 'unit', title: '单位' },
  { colKey: 'brandName', title: '品牌名称' },
  { colKey: 'specifications', title: '规格' },
  // { colKey: 'materialDataType', title: '材料类型' },
  // { colKey: 'materialNo', title: '材料编码' },
  { colKey: 'model', title: '型号' },
  { colKey: 'costPrice', title: '成本价(元)' },
  // { colKey: 'sellingPrice', title: '售价(元)' },
  { colKey: 'num', title: '数量',width:160 },
  { colKey: 'operation', title: '操作', fixed: 'right' },
];
// 处理初始化表格
const handleInitTable = () => {
  const params = {
    materialDataType: props.materialDataType,
    projectId:props.obj.id
  };
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
// 加载状态
const loadingSubmit = ref(false);
const handleReset = () => {

}
// 保存数据
const handleSave =()=>{
  const params = {
    materialDataType: props.materialDataType,
    projectId:props.obj.id,
    costList:customTableRef.value.data
  }
  updateCost(params).then(() => {
      MessagePlugin.success('更新成功');
      handleRefreshTable();
      const result ={mode:'update'}
      emits('requestSuccess',result);
      visible.value = false
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
}
// 新增弹框的保存
const handleCostSave = (selectedData: any[]) =>{
  // 过滤掉已存在的数据
  const newData = selectedData.filter((selectedItem) => {
    return !customTableRef.value.data.some((existingItem) => existingItem.id === selectedItem.id);
  });
  customTableRef.value.data = [...customTableRef.value.data, ...newData]
  
}
const handleAdd = () => {
  visibleCost.value = true
}
// 处理删除
const handleDelete = (rowIndex: number) => {
  customTableRef.value.data.splice(rowIndex, 1)
  // programmeCostCRUD
  //   .delete(params)
  //   .then(() => {
  //     MessagePlugin.success('删除成功');
  //     handleRefreshTable();
  //   })
  //   .catch(({ message }) => {
  //     MessagePlugin.error(message);
  //   });
  
};
</script>
